package cn.juque.workflow.handler;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.juque.common.base.BaseConstants;
import cn.juque.common.base.BaseOperator;
import cn.juque.common.thread.BaseOperatorThreadLocal;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 注入公共字段自动填充,任选注入方式即可
 *
 * @author huangjinghua
 */

@Slf4j
public class BaseMetaObjectHandler implements MetaObjectHandler {

    @Resource
    private BaseOperatorThreadLocal baseOperatorThreadLocal;

    /**
     * 新增填充
     * <ul>
     *     <li>可通过getFieldValByName("createDate", metaObject) 获取对应值</li>
     * </ul>
     *
     * @param metaObject : 对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
		BaseOperator baseOperator = this.baseOperatorThreadLocal.get();
        setFieldValByName("createDate", DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN), metaObject);
        setFieldValByName("createTime", new Date(), metaObject);
        setFieldValByName("updateDate", DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN), metaObject);
        setFieldValByName("updateTime", new Date(), metaObject);
        if (null == baseOperator) {
            setFieldValByName("createUserId", BaseConstants.ADMIN, metaObject);
            setFieldValByName("createOrgId", BaseConstants.ROOT, metaObject);
            setFieldValByName("updateUserId", BaseConstants.ADMIN, metaObject);
            setFieldValByName("updateOrgId", BaseConstants.ROOT, metaObject);
            return;
        }
        setFieldValByName("createUserId", baseOperator.getUserId(), metaObject);
        setFieldValByName("createOrgId", baseOperator.getOrgIdList().get(0), metaObject);
        setFieldValByName("updateUserId", baseOperator.getUserId(), metaObject);
        setFieldValByName("updateOrgId", baseOperator.getOrgIdList().get(0), metaObject);
    }

    /**
     * 更新填充
     *
     * @param metaObject : 对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName("updateDate", DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN), metaObject);
        setFieldValByName("updateTime", new Date(), metaObject);
        BaseOperator baseOperator = this.baseOperatorThreadLocal.get();
        if(null == baseOperator) {
            setFieldValByName("updateUserId", BaseConstants.ADMIN, metaObject);
            setFieldValByName("updateOrgId", BaseConstants.ROOT, metaObject);
            return;
        }
        setFieldValByName("updateUserId", baseOperator.getUserId(), metaObject);
        setFieldValByName("updateOrgId", baseOperator.getOrgIdList().get(0), metaObject);
    }
}
